﻿#region Copyright(c) Alexey Sadomov, Vladimir Timashkov, Dave Scriven, Stef Heyenrath. All Rights Reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2010 Alexey Sadomov, Vladimir Timashkov, Dave Scriven, Stef Heyenrath. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1. No Trademark License - Microsoft Public License (Ms-PL) does not grant you rights to use
//      authors names, logos, or trademarks.
//   2. If you distribute any portion of the software, you must retain all copyright,
//      patent, trademark, and attribution notices that are present in the software.
//   3. If you distribute any portion of the software in source code form, you may do
//      so only under this license by including a complete copy of Microsoft Public License (Ms-PL)
//      with your distribution. If you distribute any portion of the software in compiled
//      or object code form, you may only do so under a license that complies with
//      Microsoft Public License (Ms-PL).
//   4. The names of the authors may not be used to endorse or promote products
//      derived from this software without specific prior written permission.
//
// The software is licensed "as-is." You bear the risk of using it. The authors
// give no express warranties, guarantees or conditions. You may have additional consumer
// rights under your local laws which this license cannot change. To the extent permitted
// under your local laws, the authors exclude the implied warranties of merchantability,
// fitness for a particular purpose and non-infringement.
// -----------------------------------------------------------------------------
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Xml.Linq;
using CamlexNET.ClientObjectModel.Impl.Helpers;
using CamlexNET.ClientObjectModel.Interfaces;
using Microsoft.SharePoint.Client;

namespace CamlexNET.ClientObjectModel.Impl
{
    internal class Query : IQuery
    {
        private readonly ITranslatorFactory translatorFactory;
        private readonly List<Expression<Func<ListItem, bool>>> whereExpressions;
        private Expression<Func<ListItem, object[]>> orderByExpression;
        private Expression<Func<ListItem, object[]>> groupByExpression;
        private bool? groupByCollapse;
        private int? groupByLimit;
        private XElement viewFields;
        private int count = -1;
        
        public Query(ITranslatorFactory translatorFactory)
        {
            this.translatorFactory = translatorFactory;
            this.whereExpressions = new List<Expression<Func<ListItem, bool>>>();
        }

        public IQuery Where(Expression<Func<ListItem, bool>> expr)
        {
            whereExpressions.Add(expr);
            return this;
        }

        public IQuery WhereAll(IEnumerable<Expression<Func<ListItem, bool>>> expressions)
        {
            whereExpressions.AddRange(expressions);
            return this;
        }

        public IQuery WhereAny(IEnumerable<Expression<Func<ListItem, bool>>> expressions)
        {
            var combinedExpression = ExpressionsHelper.CombineOr(expressions);
            return this.Where(combinedExpression);
        }

        public IQuery OrderBy(Expression<Func<ListItem, object>> expr)
        {
            var lambda = Expression.Lambda<Func<ListItem, object[]>>(Expression.NewArrayInit(typeof(object), expr.Body), expr.Parameters);
            return this.OrderBy(lambda);
        }

        public IQuery OrderBy(Expression<Func<ListItem, object[]>> expr)
        {
            this.orderByExpression = expr;
            return this;
        }

        public IQuery OrderBy(IEnumerable<Expression<Func<ListItem, object>>> expressions)
        {
            if (expressions == null || !expressions.Any())
            {
                throw new EmptyExpressionsListException();
            }

            var expr = expressions.FirstOrDefault();
            if (expr == null)
            {
                throw new EmptyExpressionsListException();
            }

            var lambda = Expression.Lambda<Func<ListItem, object[]>>(
                Expression.NewArrayInit(typeof(object), expressions.Select(e => e.Body)), expr.Parameters);
            return this.OrderBy(lambda);
        }

        public IQuery GroupBy(Expression<Func<ListItem, object>> expr)
        {
            var lambda = Expression.Lambda<Func<ListItem, object[]>>(
                Expression.NewArrayInit(typeof(object), expr.Body), expr.Parameters);
            return this.GroupBy(lambda, null, null);
        }

        public IQuery GroupBy(Expression<Func<ListItem, object[]>> expr, bool? collapse, int? groupLimit)
        {
            this.groupByExpression = expr;
            this.groupByCollapse = collapse;
            this.groupByLimit = groupLimit;
            return this;
        }

        public IQuery GroupBy(Expression<Func<ListItem, object>> expr, bool? collapse, int? groupLimit)
        {
            var lambda = Expression.Lambda<Func<ListItem, object[]>>(
                Expression.NewArrayInit(typeof(object), expr.Body), expr.Parameters);
            return this.GroupBy(lambda, collapse, groupLimit);
        }

        public IQuery GroupBy(Expression<Func<ListItem, object>> expr, bool? collapse)
        {
            var lambda = Expression.Lambda<Func<ListItem, object[]>>(
                Expression.NewArrayInit(typeof(object), expr.Body), expr.Parameters);
            return this.GroupBy(lambda, collapse, null);
        }

        public IQuery ViewFields(Expression<Func<ListItem, object>> expr)
        {
            var lambda = Expression.Lambda<Func<ListItem, object[]>>(
                Expression.NewArrayInit(typeof(object), expr.Body), expr.Parameters);
            return this.ViewFields(lambda);
        }

        public IQuery ViewFields(Expression<Func<ListItem, object[]>> expr)
        {
            var translator = translatorFactory.Create(expr);
            var viewFields = translator.TranslateViewFields(expr);

            this.viewFields = viewFields;
            return this;
        }

        public IQuery GroupBy(Expression<Func<ListItem, object>> expr, int? groupLimit)
        {
            var lambda = Expression.Lambda<Func<ListItem, object[]>>(
                Expression.NewArrayInit(typeof(object), expr.Body), expr.Parameters);
            return this.GroupBy(lambda, null, groupLimit);
        }

        public IQuery Take(int count)
        {
            this.count = count;
            return this;
        }

        private XElement GetWhereElement()
        {
            if (this.whereExpressions.Count > 0)
            {
                var whereExpression = this.whereExpressions.Count == 1 ? this.whereExpressions.First() : ExpressionsHelper.CombineAnd(this.whereExpressions);
                var whereTranslator = translatorFactory.Create(whereExpression);

                return whereTranslator.TranslateWhere(whereExpression);
            }
            else
            {
                return null;
            }
        }

        private XElement GetOrderByElement()
        {
            if (this.orderByExpression != null)
            {
                var translator = translatorFactory.Create(this.orderByExpression);
                return translator.TranslateOrderBy(this.orderByExpression);
            }
            else
            {
                return null;
            }
        }

        private XElement GetGroupByElement()
        {
            if (this.groupByExpression != null)
            {
                var translator = translatorFactory.Create(this.groupByExpression);
                return translator.TranslateGroupBy(this.groupByExpression, this.groupByCollapse, this.groupByLimit);
            }
            else
            {
                return null;
            }
        }

        public XElement ToCaml()
        {
            XElement where = this.GetWhereElement();
            XElement orderBy = this.GetOrderByElement();
            XElement groupBy = this.GetGroupByElement();

            XElement query = (where != null || orderBy != null || groupBy != null) ? new XElement(Tags.Query, where, orderBy, groupBy) : null;
            XElement rowLimit = this.count >= 0 ? new XElement(Tags.RowLimit, this.count) : null;

            return new XElement(Tags.View, this.viewFields, query, rowLimit);
        }

        public CamlQuery ToCamlQuery()
        {
            var query = new CamlQuery();
            query.ViewXml = this.ToString();

            return query;
        }

        public override string ToString()
        {
            return this.ToCaml().ToString();
        }

        public static implicit operator string(Query query)
        {
            return query.ToString();
        }
    }
}